//
//  SCPhotoManager.m
//  PhotoAlbum
//
//  Created by Chao Sheng on 2021/12/1.
//

#import "SCPhotoManager.h"

@interface SCPhotoManager ()

@end

@implementation SCPhotoManager

- (instancetype)init {
    if (self == [super init]) {
        [self setup];
    }
    return self;
}

- (void)setup {
    self.rowCount = 4;
    self.photoSelectedMax = 3;
    self.editEnble = YES;
    self.ocrEnable = NO;
    self.photoViewWidth = sc_WIDTH;
}

- (void)setImgNetworkingList:(NSArray<NSString *> *)imgNetworkingList {
    _imgNetworkingList = imgNetworkingList;
    self.selectedArray = @[].mutableCopy;
    for (NSInteger i = 0; i<self.imgNetworkingList.count; i++) {
        SCPhotoModel *model = [SCPhotoModel new];
        model.imageNetworkingUrl = self.imgNetworkingList[i];
        model.isSelected = true;
        model.selectedIndex = i+1;
        model.date = [NSDate date];
        model.ocrTextUsed = true;
        [self.selectedArray addObject:model];
    }
    self.oldSelectedArray = self.selectedArray.mutableCopy;
}

- (void)setLocalImgList:(NSArray<UIImage *> *)localImgList {
    _localImgList = localImgList;
    if (!self.editEnble) {
        self.selectedArray = @[].mutableCopy;
        for (NSInteger i = 0; i<self.localImgList.count; i++) {
            SCPhotoModel *model = [SCPhotoModel new];
            model.highQualityImage = self.localImgList[i];
            model.tempImage = model.highQualityImage;
            model.isSelected = true;
            model.selectedIndex = i+1;
            model.date = [NSDate date];
            model.ocrTextUsed = true;
            model.imgSize = model.highQualityImage.size;
            [self.selectedArray addObject:model];
        }
        self.oldSelectedArray = self.selectedArray.mutableCopy;
    }
}

- (void)updateManagerAfterSaved:(NSArray *)urlList{
    for (NSInteger i = 0; i < urlList.count; i++)
    {
        SCPhotoModel *obj = self.selectedArray[i];
        obj.imageNetworkingUrl = urlList[i];
    }
    self.oldSelectedArray = self.selectedArray.mutableCopy;
}

// 通过时间排序获取照片
- (void)getAllPhotoAlbumListByDateCompletion:(void (^)(NSArray<SCPhotoDateModel *> * _Nonnull, NSArray<SCPhotoModel *> * _Nonnull, NSInteger))completion {
    NSMutableArray *assetList = @[].mutableCopy;
    //获取智能相册
    PHFetchResult *smartFecthResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];
    [smartFecthResult enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(PHAssetCollection *collection, NSUInteger idx, BOOL * _Nonnull stop) {
        // 是否按创建时间排序
        PHFetchOptions *option = [[PHFetchOptions alloc] init];
        option.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
        //照片
        option.predicate = [NSPredicate predicateWithFormat:@"mediaType == %ld", PHAssetMediaTypeImage];
        //获取照片集合
        PHFetchResult *result = [PHAsset fetchAssetsInAssetCollection:collection options:option];
        // 过滤掉空相册
        if(result>0 && ![[SCPhotoTools transFormPhotoTitle:collection.localizedTitle] isEqualToString:@"最近删除"]) {
            //单个图片的信息都保存在PHAsset中
            for (PHAsset *asset in result) { //不显示gif和livePhoto
                if (![assetList containsObject:asset] && asset.mediaSubtypes != PHAssetMediaSubtypePhotoLive && ![self isGif:asset]) {
                    [assetList addObject:asset];
                }
            }
        }
    }];
    
    // 获取用户相册
    PHFetchResult *usrFecthResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    [usrFecthResult enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(PHAssetCollection *collection, NSUInteger idx, BOOL * _Nonnull stop) {
        // 是否按创建时间排序
        PHFetchOptions *option = [[PHFetchOptions alloc] init];
        option.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
        //照片
        option.predicate = [NSPredicate predicateWithFormat:@"mediaType == %ld", PHAssetMediaTypeImage];
        //获取照片集合
        PHFetchResult *result = [PHAsset fetchAssetsInAssetCollection:collection options:option];
        // 过滤掉空相册
        if(result>0) {
            //单个图片的信息都保存在PHAsset中
            for (PHAsset *asset in result) {
                if (![assetList containsObject:asset] && asset.mediaSubtypes != PHAssetMediaSubtypePhotoLive && ![self isGif:asset]) {
                    [assetList addObject:asset];
                }
            }
        }
    }];
    
    //assetList按时间排序(升序)
    NSArray *newAssetList = [assetList sortedArrayWithOptions:NSSortConcurrent usingComparator:^NSComparisonResult(PHAsset *obj1, PHAsset *obj2) {
        
       NSTimeInterval time1 = [obj1.creationDate timeIntervalSince1970];
       NSTimeInterval time2 = [obj2.creationDate timeIntervalSince1970];
 
       NSComparisonResult result = [@(time1) compare:@(time2)];
       
       return result == NSOrderedDescending; //升序
        
   }];

    
    NSDate *currentDate = nil;
    NSMutableArray *allDateList = @[].mutableCopy;
    NSMutableArray *allPhotoList = @[].mutableCopy;
    NSMutableArray *sameDateList;
    SCPhotoDateModel *dateModel;
    NSInteger section = 0;
    NSInteger row = 0;
    NSMutableArray *selectList = self.selectedArray.mutableCopy;
    for(PHAsset *asset in newAssetList) {
        if (!currentDate) {
            dateModel = [SCPhotoDateModel new];
            dateModel.date = asset.creationDate;
            sameDateList = @[].mutableCopy;
            
            SCPhotoModel *photoModel = [SCPhotoModel new];
            photoModel.asset = asset;
            photoModel.row = row;
            photoModel.section = section;
    
            [self filterSelectedModel:photoModel InList:selectList];
            
            [sameDateList addObject:photoModel];
            [allPhotoList addObject:photoModel];
            currentDate = asset.creationDate;
            
        } else {
            /// 同一时间的
            if ([SCPhotoTools isSameDay:asset.creationDate date2:currentDate]) {
                SCPhotoModel *photoModel = [SCPhotoModel new];
                photoModel.asset = asset;
                photoModel.row = row++;
                photoModel.section = section;
                
                [self filterSelectedModel:photoModel InList:selectList];
                
                [sameDateList addObject:photoModel];
                [allPhotoList addObject:photoModel];
                
                //最后的照片存储
                if(asset==newAssetList.lastObject) {
                    dateModel.photoList = sameDateList.copy;
                    [allDateList addObject:dateModel];
                }
                
            } else {
                /// 不同时间
                dateModel.photoList = sameDateList.copy;
                [allDateList addObject:dateModel];
                //sameDateList\dateModel重新赋值
                dateModel = [SCPhotoDateModel new];
                dateModel.date = asset.creationDate;
                sameDateList = @[].mutableCopy;
                SCPhotoModel *photoModel = [SCPhotoModel new];
                photoModel.asset = asset;
                photoModel.row = 0;
                row = 0;
                photoModel.section = section++;
                
                [self filterSelectedModel:photoModel InList:selectList];
                
                [sameDateList addObject:photoModel];
                [allPhotoList addObject:photoModel];
            
                currentDate = asset.creationDate;
                
                //最后的照片存储
                if(asset==newAssetList.lastObject) {
                    dateModel.photoList = sameDateList.copy;
                    [allDateList addObject:dateModel];
                }

            }
        }
    }
    
//    self.oldSelectedArray = self.selectedArray.mutableCopy;
//    NSLog(@"%@=%ld",allPhotoList.lastObject,allPhotoList.count);
//    SCPhotoDateModel*model = allDateList.lastObject;
//    NSLog(@"%@=%ld",model.photoList.lastObject,newAssetList.count);
    completion(allDateList,allPhotoList,newAssetList.count);
    
}

//筛选出已经选中的asset
- (void)filterSelectedModel:(SCPhotoModel*)photoModel InList:(NSMutableArray*)selectList {
    if (selectList.count > 0) {
        NSString *property = @"asset";
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"%K = %@", property, photoModel.asset];
        NSArray *newArray = [selectList filteredArrayUsingPredicate:pred];
        if (newArray.count > 0) {
            SCPhotoModel *model = newArray.firstObject;
            [selectList removeObject:model];
            photoModel.isSelected = true;
            photoModel.selectedIndex = [self.selectedArray indexOfObject:model] + 1;
            photoModel.imageNetworkingUrl = model.imageNetworkingUrl;
            photoModel.highQualityImage = model.highQualityImage;
            [self.selectedArray replaceObjectAtIndex:[self.selectedArray indexOfObject:model] withObject:photoModel];
            if ([self.oldSelectedArray containsObject:model]) {
                [self.oldSelectedArray replaceObjectAtIndex:[self.oldSelectedArray indexOfObject:model] withObject:photoModel];
            }
        }
    }
}

- (BOOL)isGif:(PHAsset*)asset {
    return [[asset valueForKey:@"filename"] hasSuffix:@"GIF"];
}

@end
